from playwright.sync_api import sync_playwright, TimeoutError
import random
import time

def SearchSuggestions(playwright_instance=None):
    # 如果没有传入playwright实例，则创建新的实例
    if playwright_instance is None:
        with sync_playwright() as p:
            return SearchSuggestions(p)
    
    # 使用传入的playwright实例
    p = playwright_instance
    # 标记浏览器实例来源（如果有传入playwright实例，则不是内部创建的浏览器）
    is_external_browser = playwright_instance is not None
    # 启动浏览器
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()

    try:
        # 导航到必应
        page.goto('https://cn.bing.com', wait_until='networkidle')
        
        # 找到搜索框
        search_box = page.locator('#sb_form_q')
        
        # 最多尝试3次
        max_retries = 3
        for attempt in range(max_retries):
            try:
                # 点击搜索框并输入空格来触发推荐
                search_box.click()
                search_box.fill(" ")
                
                # 等待推荐列表出现
                suggestion_list = page.locator('#sw_as')
                suggestion_list.wait_for(state='visible', timeout=8000)  # 增加等待时间到8秒
                
                # 确保推荐列表完全加载
                time.sleep(1)
                
                # 获取所有推荐项
                suggestions = page.locator('#sw_as li')
                count = suggestions.count()
                
                if count > 0:
                    # 随机选择一个推荐项
                    random_index = random.randint(0, count - 1)
                    selected_item = suggestions.nth(random_index)
                    selected_text = selected_item.inner_text()
                    print("选择第 %d 个推荐项：%s" % (random_index + 1, selected_text))
                    
                    # 确保元素可点击
                    selected_item.wait_for(state='visible')
                    selected_item.click()
                    break  # 成功后退出重试循环
                else:
                    print(f"尝试 {attempt + 1}/{max_retries}: 推荐列表为空，重试...")
                    if attempt == max_retries - 1:
                        print("达到最大重试次数，执行默认搜索")
                        page.keyboard.press('Enter')
            except TimeoutError:
                print(f"尝试 {attempt + 1}/{max_retries}: 等待推荐列表超时")
                if attempt == max_retries - 1:
                    print("达到最大重试次数，执行默认搜索")
                    page.keyboard.press('Enter')
                else:
                    # 清空搜索框，准备重试
                    search_box.fill("")
                    time.sleep(1)
        # 等待搜索结果加载
        page.wait_for_load_state('networkidle')
        # 等待一会儿以查看结果
        page.wait_for_timeout(3000)
    except Exception as e:
        print(f"发生错误：{e}")
    finally:
        if not is_external_browser:
            # 只有在内部创建实例时，才关闭浏览器和页面
            page.close()
            browser.close()
        else:
            # 对于外部传入的实例，只关闭页面，保持浏览器开启
            page.close()

if __name__ == '__main__':
    SearchSuggestions()